package cqrtplm.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.user.controller.TyplmTeamController;
import com.ty.basic.entity.PrincipalEntity;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.dto.GroupSegmNumDTO;
import cqrtplm.dto.query.RtSegmNumQueryDTO;
import cqrtplm.entity.RtSegmNumDO;
import cqrtplm.mapper.RtSegmNumMapper;
import cqrtplm.service.RtSegmNumService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RtSegmNumServiceImpl implements RtSegmNumService {

    private String jsonTem = "{\"userID\":\"admin\",\"params\":[{\"curPage\":1,\"pageSize\":99,\"otype\":\"ty.inteplm.org.CTyGroup\",\"oid\":\"728671870369726464\"}]}";

    @Autowired
    private RtSegmNumMapper rtSegmNumMapper;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private TyplmTeamController typlmTeamController;

    @Override
    public int save(RtSegmNumDO record) {
        UserDO user = TyAccountContext.getUser();
        record.setCreateUser(user.getFullname()+"("+user.getName()+")");
        record.setCreateUserCname(user.getFullname());
        return rtSegmNumMapper.insert(record);
    }

    @Override
    public int update(RtSegmNumDO record) {
        UserDO user = TyAccountContext.getUser();
        record.setUpdateUser(user.getFullname()+"("+user.getName()+")");
        record.setUpdateUserCname(user.getFullname());
        if(record.getEnabled()){
            record.setEnabledUser(user.getFullname()+"("+user.getName()+")");
            record.setEnabledUserCname(user.getFullname());
        }else {
            record.setEnabledUser(null);
            record.setEnabledUserCname(null);
        }
        return rtSegmNumMapper.update(record);
    }

    @Override
    public int delete(String id) {
        return rtSegmNumMapper.delete(id);
    }

    @Override
    public RtSegmNumDO getById(String id) {
        return rtSegmNumMapper.selectById(id);
    }

    @Override
    public List<RtSegmNumDO> listAll(RtSegmNumQueryDTO dto) {
        return rtSegmNumMapper.selectAll(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult biding(GroupSegmNumDTO dto) {
        //获取当前登录人
        UserDO user = TyAccountContext.getUser();
        //获取当前时间
        Date startDate = new Date();

        List<GroupSegmNumDTO.GroupDTO> groupDTOList = dto.getGroupDTOList();
        List<GroupSegmNumDTO.SegmNumDTO> segmNumDTOList = dto.getSegmNumDTOList();

        if(IterUtil.isNotEmpty(groupDTOList)){
            groupDTOList.stream().forEach(i->{
                i.setKeyId(snowflakeIdComponent.getInstance().nextId().toString());
                i.setCreateUser(user.getName());
                i.setCreateTime(startDate);
                if(IterUtil.isNotEmpty(segmNumDTOList)){
                    // 提取 segmNumId 字段并用逗号拼接
                    String result = segmNumDTOList.stream()
                            .map(GroupSegmNumDTO.SegmNumDTO::getSegmNumId) // 提取 segmNumId 字段
                            .map(String::valueOf) // 确保值是字符串类型
                            .collect(Collectors.joining(",")); // 用逗号拼接
                    List<String> list = rtSegmNumMapper.selectGroupSegmByGroupId(i.getGroupId());
                    if(IterUtil.isNotEmpty(list)){
                        rtSegmNumMapper.deleteGroupSegmByGroupId(i.getGroupId());
                    }
                    rtSegmNumMapper.insertByGroupAndSegm(i,result,dto.getDrawingMaterialAuth());
                }
            });
        }
        return ResponseResult.result("绑定成功");
    }


    @Override
    public ResponseResult getGroupSegm(String groupId) {
        List<String> list = rtSegmNumMapper.selectGroupSegmByGroupId(groupId);
        return ResponseResult.success(list);
    }

    @Override
    public ResponseResult getSegmNumIdPower(String segmNumId) {
        //默认无搭建BOM权限
        boolean bo = false;
        //获取当前登录人
        UserDO user = TyAccountContext.getUser();
        //通过底层方法获取用户下面的群组
        List<String> groupIds = this.getGroupByUserId(user);
        if(IterUtil.isNotEmpty(groupIds)){
            List<String> segm = rtSegmNumMapper.selectSegmByGroupIds(groupIds,segmNumId);
            if(IterUtil.isNotEmpty(segm)){
                bo = true;
            }
        }
        return ResponseResult.success(bo);
    }

    @Override
    public String getDrawingMaterialAuth(String segmNumId) {

        //获取当前登录人
        UserDO user = TyAccountContext.getUser();
        //通过底层方法获取用户下面的群组
        List<String> groupIds = this.getGroupByUserId(user);
        if(IterUtil.isNotEmpty(groupIds)){
            List<String> drawingMaterialAuths = rtSegmNumMapper.selectAuthByGroupIds(groupIds,segmNumId);
            if(IterUtil.isNotEmpty(drawingMaterialAuths)){
                return String.join(",", drawingMaterialAuths);
            }
        }
        return "";
    }

    /**
     * @param category
     * @return
     */
    @Override
    public JSONObject querySegmNumByCategory(String category) {
        JSONObject jsonObject = new JSONObject();
        List<RtSegmNumDO> list =null;
        if (StringUtils.isBlank(category)) {
            list = rtSegmNumMapper.querySegmNumByCategory(category);
        }else{
            list = rtSegmNumMapper.querySegmNumByCategory(category);
            if(CollUtil.isEmpty(list)|| list.size()>1){
                list = rtSegmNumMapper.selectAll(new RtSegmNumQueryDTO());
            }
        }
        if(CollUtil.isNotEmpty(list)){
            for (RtSegmNumDO rtSegmNumDO : list){
                jsonObject.put(rtSegmNumDO.getId(),rtSegmNumDO.getPosition());
            }
        }
        return jsonObject;
    }

    private List<String> getGroupByUserId(UserDO user) {
        JSONObject jsonObject = JSON.parseObject(jsonTem);
        List<String> groupList = new ArrayList<>();
        // 替换字段值
//        jsonObject.put("userID", user.getName());  // 替换 userID 的值
        jsonObject.getJSONArray("params").getJSONObject(0).put("oid", user.getOid());  // 替换 oid 的值
        jsonObject.getJSONArray("params").getJSONObject(0).put("otype", "ty.inteplm.org.CTyUser");  // 替换 otype 的值
        ResponseResult<List<PrincipalEntity>> parentGroup = typlmTeamController.getParentGroup(jsonObject);
        List<PrincipalEntity> data = parentGroup.getData();
        if(IterUtil.isNotEmpty(data)){
            groupList = data.stream()
                    .map(PrincipalEntity::getOid)
                    .map(String::valueOf)
                    .collect(Collectors.toList());

        }
        return groupList;
    }
}
